<%--
  Created by IntelliJ IDEA.
  User: 败絮
  Date: 2021/8/6
  Time: 13:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8"  isELIgnored="false" %>

<%--<%@page isELIgnored="false" %>--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>员工列表</title>
    <%
        pageContext.setAttribute("APP_PATH", request.getContextPath());
    %>
    <script type="text/javascript" src="static/js/jquery.js"></script>
    <link rel="stylesheet" href="static/bootstrap-3.4.1-dist/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="static/bootstrap-3.4.1-dist/js/bootstrap.min.js"
            integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
</head>
<body>
<!-- 员工修改模态框 -->
<div class="modal fade" id="empUpdateModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" >修改</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <p class="form-control-static" id="empName_update_static"></p>

                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="text"  name="email" class="form-control" id="email_update_input" placeholder="email@qq.com">
                            <span  class="help-block"> </span>

                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender1_update_input" value="M" checked="checked"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender2_update_input" value="F"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">deptName</label>
                        <div class="col-sm-3">
                            <%--                            部门提交部门id--%>
                            <select class="form-control" name="dId" id="dept_add_select">

                            </select>
                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_update_btn">更新</button>
            </div>
        </div>
    </div>
</div>
<!-- 员工添加模态框 -->
<div class="modal fade" id="empAddModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">员工添加</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <input type="text"  name="empName" class="form-control" id="empName_add_input" placeholder="empName">
                            <span  class="help-block"> </span>

                        </div>>
                        </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="text"  name="email" class="form-control" id="email_add_input" placeholder="email@qq.com">
                            <span  class="help-block"> </span>

                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender1_add_input" value="M" checked="checked"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender2_add_input" value="F"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">deptName</label>
                        <div class="col-sm-3">
<%--                            部门提交部门id--%>
                            <select class="form-control" name="dId" id="dept_add_select">

                            </select>
                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
            </div>
        </div>
    </div>
</div>

<div class="container">
    <%--    标题--%>
    <div class="row">
        <div class="col-md-12">
            <h1>SSM-CRUD</h1>
        </div>
    </div>
    <%--    新增，删除按钮、、--%>
    <div class="row">
        <div class="col-md-4 col-md-offset-10">
            <button class="btn btn-primary" id="emp_add_model_btn">新增</button>
            <button class="btn btn-danger" id="emp_delete_all_btn">删除</button>
        </div>
    </div>
    <%--    显示表格数据--%>
    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover" id="emps_table">
                <thead>
                <tr>
                    <th>
                        <input type="checkbox" id="check_all"/>
                    </th>
                    <th>#</th>
                    <th>empName</th>
                    <th>gender</th>
                    <th>email</th>
                    <th>deptName</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>

                </tbody>
            </table>
        </div>
    </div>
    <%--    显示分页信息--%>
    <div class="row">
        <%--        分页文字信息--%>
        <div class="col-md-6" id="page_info_area">

        </div>
        <%--    分页条--%>
        <div class="col-md-6" id="page_nav_area">

        </div>
    </div>

</div>
<script type="text/javascript">
    var totalRecord,currentPage;
    //1.页面加载完成以后，直接发送一个ajax请求，要到分页数据
    $(function () {
        //去首页
        to_page(1);
    });
    function to_page(pn) {
        $.ajax({
            url:"${APP_PATH}/emps",
            data:"pn="+pn,
            type:"GET",
            success:function (msg) {
                //1.解析并显示员工数据
                build_emps_table(msg);
                //解析显示分页信息
                build_page_info(msg)
                //解析显示分页条数据
                build_page_nav(msg);
            }
        });
    }
    function build_emps_table(msg) {
        //清空table
        $("#emps_table tbody").empty();
    var emps=msg.extend.page.list;
    $.each(emps,function (index,item) {
        var checkBox=$("<td><input type='checkbox' class='check_item'></td>");
        var empTd=$("<td></td>").append(item.empId);
        var empNameTd=$("<td></td>").append(item.empName);
        var emailTd=$("<td></td>").append(item.email);
        var deptNameTd=$("<td></td>").append(item.dept.deptName);
        var genderTd=$("<td></td>").append(item.gender=="M"?"男":"女");
        var editBtn=$("<button></button>").addClass("btn btn-primary btn-sm edit_btn").append($("<span></span>")
            .addClass("glyphicon glyphicon-pencil")).append("编辑");
        //为编辑按钮添加一个自定义属性，来表示当前员工id
        editBtn.attr("edit-id",item.empId);
        var deleteBtn=$("<button></button>").addClass("btn btn-danger btn-sm delete_btn").append($("<span></span>")
            .addClass("glyphicon glyphicon-trash")).append("删除");
        //为删除按钮添加一个自定义属性，来表示当前员工id
        deleteBtn.attr("del-id",item.empId);
        var btnTd=$("<td></td>").append(editBtn).append(" ").append(deleteBtn);

        $("<tr></tr>").append(checkBox)
            .append(empTd)
            .append(empNameTd)
            .append(genderTd)
            .append(emailTd)
            .append(deptNameTd)
            .append(btnTd)
            .appendTo("#emps_table tbody");
    });
    }
    //解析显示分页信息
    function build_page_info(msg) {
        //清空数据
        $("#page_info_area").empty();
        $("#page_info_area").append("当前第"+msg.extend.page.pageNum+"页，" +
            "总共"+msg.extend.page.pages+"页,总共"+msg.extend.page.total+"条记录");
        totalRecord=msg.extend.page.total;
        currentPage=msg.extend.page.pageNum;
    }
    //解析分页条,点击分页要能去指定页面
    function build_page_nav(msg) {
        //清空数据
        $("#page_nav_area").empty();
        //构建元素
        var ul=$("<ul></ul>").addClass("pagination");
        var firstPageLi=$("<li></li>").append($("<a></a>").append("首页").attr("href","#"));
        var prePage=$("<li></li>").append($("<a></a>").append("&laquo;"));
        if (msg.extend.page.hasPreviousPage==false){
            firstPageLi.addClass("disabled");
            prePage.addClass("disabled");
        }else {
            firstPageLi.click(function () {
                to_page(1);
            });
            prePage.click(function () {
                to_page(+msg.extend.page.pageNum-1);
            });
        }
        //为元素添加单击跳转事件

        var nextPage=$("<li></li>").append($("<a></a>").append("&raquo;"));
        var lastPageLi=$("<li></li>").append($("<a></a>").append("末页").attr("href","#"));
        if (msg.extend.page.hasNextPage==false){
            nextPage.addClass("disabled");
            lastPageLi.addClass("disabled");
        }else {
            nextPage.click(function () {
                to_page(+msg.extend.page.pageNum+1);
            });
            lastPageLi.click(function () {
                to_page(+msg.extend.page.pages);
            });
        }

        ul.append(firstPageLi).append(prePage);
        $.each(msg.extend.page.navigatepageNums,function (index,item) {

                var numLi=$("<li></li>").append($("<a></a>").append(item));
                if (msg.extend.page.pageNum==item){
                    numLi.addClass("active");
                }
                numLi.click(function () {
                      to_page(item);
                })
                ul.append(numLi);
        });
        ul.append(nextPage).append(lastPageLi);
        var navEle=$("<nav></nav>").append(ul);
        navEle.appendTo("#page_nav_area");
    }
    //点击新增按钮弹出模态框
    $("#emp_add_model_btn").click(function () {
        //发送ajax请求，查出部门信息，显示在下拉列表中
        getDepts("#empAddModel select");
        //弹出模态框
        $("#empAddModel").modal({
            backdrop:"static"
        });
    });
    //查出所有的部门信息
    function getDepts(ele) {
        //清空
        $("ele").empty();

        $.ajax({
            url: "${APP_PATH}/depts",
            type: "GET",
            success:function (msg) {
               //显示部门信息在下拉列表中

                $.each(msg.extend.depts,function () {
                    var optionEle=$("<option></option>").append(this.deptName).attr("value",this.deptId);
                    optionEle.appendTo(ele);
                })
            }
        })
    }
    //校验方法
    function validate_add_form(){
        //拿到要校验的数据,使用正则表达式
     var empName= $("#empName_add_input").val();
     var regName=/(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
     if(!regName.test(empName)){
         //alert("用户名可以是2-5位中文，6-16英文")
         show_validate_msg("#empName_add_input","error","用户名可以是2-5位中文，6-16英文");
      /*   $("#empName_add_input").parent().addClass("has-error");
         $("#empName_add_input").next("span").text("用户名可以是2-5位中文，6-16英文");*/
         return false;
         }else {
         // $("#empName_add_input").parent().addClass("has-success");
         show_validate_msg("#empName_add_input","success","");
         }
      //校验邮箱信息
        var email=$("#email_add_input").val();
        var regEmail=/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})/;
        if (!regEmail.test(email)){


           // alert("邮箱格式不正确");
         /*   $("#email_add_input").parent().addClass("has-error");
            $("#email_add_input").next("span").text("邮箱格式不正确");*/
            show_validate_msg("#email_add_input","error","邮箱格式不正确");
            return  false;
        }else {
            // $("#email_add_input").parent().addClass("has-success");
            show_validate_msg("#email_add_input","success","");
        }
        return true;

    }
//显示检验结果信息
    function show_validate_msg(element,status,msg){
        //清除当前元素校验状态
        $(element).parent().removeClass("has-success has-error");
        $(element).next("span").text("");
        if ("success"==status){
            $(element).parent().addClass("has-success");
            $(element).next("span").text(msg);
        }else if("error"==status){
            $(element).parent().addClass("has-error");
            $(element).next("span").text(msg);
        }
    }
    //校验用户名是否可用
   /* $("#empName_add_input").onchange(function () {

        //发送ajax请求校验用户名是否可用
        var empName=this.value();
        $.ajax({
            url:"${APP_PATH}/checkUser",
            data:"empName="+empName,
            type:"POST",
            success:function (msg) {
            if (msg.code==100){
                show_validate_msg("#empName_add_input","success","用户名可用");
               }else {
                show_validate_msg("#empName_add_input","error","用户名已存在");
             }
            }
        })

    })*/
    //点击保存，
    $("#emp_save_btn").click(function () {
        //先对要提交的服务器进行校验
        if (!validate_add_form()){
            return false;
        }

        //将模态框中填写的数据提交给服务器进行保存

      $.ajax({
            url:"${APP_PATH}/emp",
            type:"POST",
            data:  $("#empAddModel form").serialize(),
          success:function (msg) {
            //alert(msg.msg);

              if (msg.code==100){
                  // 员工保存成功
                  //1.关闭模态框
                  $("#empAddModel").modal('hide');
                  //2.来到末页显示刚刚添加的员工,发送ajax请求显示最后一页
                  to_page(totalRecord);
              }else {
                  //显示失败信息
                  if (undefined!=msg.extend.errorFields.email){
                      //邮箱错误信息
                      show_validate_msg("#email_add_input","error",msg.extend.errorFields.email);
                  }
                  if (undefined!=msg.extend.errorFields.empName){
                      //员工姓名错误信息
                      show_validate_msg("#empName_add_input","error",msg.extend.errorFields.empName);
                  }
              }

          }
        });

    });
    //创建按钮的时候就绑定，旧版本使用live，新版本使用on
    $(document).on("click",".edit_btn",function () {
        //alert("edit")
        // 查出部门信息并显示部门列表,并且还要查出员工信息，显示员工姓名
        getDepts("#empUpdateModel select");
        getEmp($(this).attr("edit-id"));
        //把员工id传递过去，给更新按钮
        $("#emp_update_btn").attr("edit-id",$(this).attr("edit-id"))
        //弹出模态框
        $("#empUpdateModel").modal({
            backdrop:"static"
        });
    });

    function getEmp(id) {
            $.ajax({
                url:"${APP_PATH}/emp/"+id,
                type:"GET",
                success:function (msg) {
                   console.log(msg);
                    var empData=msg.extend.emp;
                    $("#empName_update_static").text(empData.empName);
                    $("#email_update_input").val(empData.email);
                    $("#empUpdateModel input[name=gender]").val([empData.gender]);
                    $("empUpdateModel select ").val([empData.dId]);
                }
            });
    }
    //点击更新，更新员工信息
    $("#emp_update_btn").click(function () {
        //校验邮箱信息
        var email=$("#email_update_input").val();
        var regEmail=/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})/;
        if (!regEmail.test(email)){

            show_validate_msg("#email_update_input","error","邮箱格式不正确");
            return  false;
        }else {
            // $("#email_add_input").parent().addClass("has-success");
            show_validate_msg("#email_update_input","success","");
        }
        //发送ajax请求保存更新的员工的数据
        $.ajax({
            url:"${APP_PATH}/emp/"+$(this).attr("edit-id"),
            type:"PUT",
            data:$("#empUpdateModel form").serialize(),
            success:function (msg) {
               // alert(msg.msg);
                //关闭对话框，回到本页面
                $("#empUpdateModel").modal("hide");
                to_page(currentPage);
            }
        });
    });
    //单个删除
    $(document).on("click",".delete_btn",function () {
        //1.弹出确认删除模态框
        //确认删除员工姓名
     var empName= $(this).parents("tr").find("td:eq(2)").text();
      var empId= $(this).attr("del-id");
     if (confirm("确认删除【"+empName+"】吗")){
         //确认 发送ajax请求
         $.ajax({
             url:"${APP_PATH}/emp/"+empId,
             type:"DELETE",
             success:function (msg) {
                    //alert(msg.msg);
                 //回到本页面
                 to_page(currentPage);
             }
         })
     }
    });
    //完成全选/全不选
    $("#check_all").click(function () {
        //attr获取checked是undefined,我们这些dom原生的属性
        //attr获取自定义属性的值，,prop修改和读取dom原生属性的值
           // $(this).prop("checked");
            $(".check_item").prop("checked", $(this).prop("checked"));
    });
    //check_item
    $(document).on("click",".check_item",function () {
        //判断当前选中的元素是不是5个
      var flag= $(".check_item:checked").length==$(".check_item").length;
        $("#check_all").prop("checked",flag);
    });
    //点击全不删除就批量删除
    $("#emp_delete_all_btn").click(function () {
        var empNames="";
        var del_idstr="";

        $.each( $(".check_item:checked"),function () {
            empNames+=$(this).parents("tr").find("td:eq(2)").text()+",";
            //组装员工id字符串
            del_idstr+=$(this).parents("tr").find("td:eq(1)").text()+"-";


        });
        //去除empNames多余的，
        empNames= empNames.substring(0,empNames.length-1);
        // 去除del_idstr多余的-
        del_idstr=del_idstr.substring(0,del_idstr.length-1);
        if (confirm("确认删除【"+empNames+"】吗")){
            //确认 发送ajax请求
            $.ajax({
                url:"${APP_PATH}/emp/"+del_idstr,
                type:"DELETE",
                success:function (msg) {
                   // alert(msg.msg);
                    //回到当前页面
                    to_page(currentPage);
                }
            })

        }
    });

</script>
</body>
</html>


